#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>


pthread_mutex_t taxi = PTHREAD_MUTEX_INITIALIZER;		//互斥变量初始化
pthread_cond_t  look = PTHREAD_COND_INITIALIZER;			//条件变量初始化


//汽车模板
struct taxi
{
	struct text* next;
	 int num;
};

struct taxi* head = NULL;								//头指针

//生产者
void* producer(void* agr)
{
	pthread_detach(pthread_self());
	printf("开始生产\n");
	int i = 1;
	struct taxi* tx;
	while(1)
	{
		tx = (struct taxi*)malloc(sizeof(struct taxi));
		if(tx == NULL)
		{
			perror("malloc");
			return NULL;
		}
		tx->num = i++;
		printf("开始生产第%d台\n", tx->num);
		pthread_mutex_lock(&taxi);
		tx->next = NULL;
		head = tx;
		pthread_cond_signal(&look);						//通知消费者
		pthread_mutex_unlock(&taxi);
		sleep(2);
	}
	
	pthread_exit(0);
}

//消费者
void* consumer(void* agr)
{
	pthread_detach(pthread_self());
	struct taxi* tx;
	while(1)
	{
		pthread_mutex_lock(&taxi);
		while(head == NULL)
		{
			//没有资源就等待
			pthread_cond_wait(&look, &taxi);
		}
		//有资源开始消费
		tx = head;
		head = tx->next;
		printf("%d已被消费\n",tx->num);
		free(tx);
		pthread_mutex_unlock(&taxi);
	

	}



	pthread_exit(0);

}


//=========================

int main()
{
	pthread_t tid1, tid2;
	int ret = 0;

	//线程创建
	pthread_create(&tid1, NULL, producer, NULL);			//生产者
	pthread_create(&tid2, NULL, consumer, NULL);			//消费者

	while(1)
	{
		sleep(1);
	}
	return 0;
}
